package c.x.jy.common.mqtt;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import c.x.jy.common.utils.HttpUtil;
public class Mqtt {

	
	public static void run( ) {
        String subTopic = "testtopic/#";
        String pubTopic = "testtopic/1";
        String content = "{\"hao\",\"123\"}";
        int qos = 2;
        String broker = "tcp://47.112.194.147:1883";
        String clientId = "emqx_test";
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            MqttClient client = new MqttClient(broker, clientId, persistence);

            // MQTT 连接选项
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setUserName("jywl");
            connOpts.setPassword("123455".toCharArray());
            // 保留会话
            connOpts.setCleanSession(true);
            connOpts.setAutomaticReconnect(true);
            // 设置回调
            client.setCallback(new PushCallback());

            // 建立连接
            System.out.println("Connecting to broker: " + broker);
            client.connect(connOpts);

            System.out.println("Connected");
            System.out.println("Publishing message: " + content);

            // 订阅
            client.subscribe(subTopic);

            // 消息发布所需参数
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(qos);
            client.publish(pubTopic, message);
            System.out.println("Message published");

          //  client.disconnect();
            System.out.println("Disconnected");
         //  client.close();
          //  System.exit(0);
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }
	
	
	public static void main(String[] args) {
		
 // 	Mqtt.run();
	 	String clientid="/jiayuan";
	 	 HttpUtil.sendget( "api/v2/nodes/emq@127.0.0.1/clients"+clientid);
		
	}
	 
}
